#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/11/25 14:38
# @Author : luhongxuan
# @Site :
# @File : json_utils.py
# @Software: PyCharm
import uuid
import json
from datetime import datetime, date


class CJsonEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        elif isinstance(obj, uuid.UUID):
            return str(obj)
        else:
            return super().default(obj)


class JSONHelper(object):
    @staticmethod
    def obj_to_json(obj):
        return json.dumps(obj, ensure_ascii=False, default=None, cls=CJsonEncoder)

    @staticmethod
    def json_to_obj(json_str, object_hook=None):
        return json.loads(json_str, object_hook=object_hook)

    @staticmethod
    def obj_to_json_file(obj, file_path):
        with open(file_path, 'w') as fp:
            return json.dump(obj, fp, ensure_ascii=False, default=None, cls=CJsonEncoder)

    @staticmethod
    def json_file_to_obj(file_path, object_hook=None, encoding='utf8'):
        with open(file_path, 'rb') as fp:
            return json.load(fp, object_hook=object_hook, encoding=encoding)
